package com.navidove.appspotlight.model.service.impl;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.navidove.appspotlight.model.bo.AppDevice;
import com.navidove.appspotlight.model.dao.AppItemDao;
import com.navidove.appspotlight.model.service.FrontService;

@Service
public class FrontServiceImpl implements FrontService {

	@Autowired
	private AppItemDao appItemDao;
	
	@SuppressWarnings("unchecked")
	public List<Map<String,Object>> getAppItemMapList() {
		DetachedCriteria criteria = DetachedCriteria.forClass(AppDevice.class);
		criteria.createAlias("appItem", "appItem");
		criteria.createAlias("appItem.appSource", "appSource");
		criteria.createAlias("appItem.appCategory", "appCategory");
		criteria.createAlias("iconImage", "iconImage");
		criteria.add(Restrictions.eq("appItem.enable", Boolean.TRUE));
		criteria.add(Restrictions.eq("enable", Boolean.TRUE));	
		criteria.addOrder(Order.asc("appSource.dictionaryCode"));
		
		criteria.setProjection(Projections.projectionList().
				add(Projections.alias(Projections.groupProperty("appItem.id"), "id")).
				add(Projections.alias(Projections.groupProperty("appItem.appName"), "appName")).
				add(Projections.alias(Projections.groupProperty("appSource.id"), "sourceId")).
				add(Projections.alias(Projections.groupProperty("appSource.dictionaryName"), "sourceName")).
				add(Projections.alias(Projections.groupProperty("appCategory.id"), "categoryId")).
				add(Projections.alias(Projections.groupProperty("appCategory.dictionaryName"), "categoryName")).
				add(Projections.alias(Projections.max("iconImage.id"), "imageId"))
				);
		criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);

		return (List<Map<String,Object>>) appItemDao.getListByCriteria(criteria);
	}
}
